<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 积分专区
 */
class AfterOrder extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


//

    public function test()
    {
        return var_dump(213123);
//        $levelList = Db::name("level")->select();
//        $user = DB::name('userhome')->where(['id' => 625])->lock(true)->find();
//        if ($user) {
//            foreach ($levelList as $key => $level) {
//                if ($level['levelId'] == ($user['levelId'] + 1)) {
//                    $levelIntegral = $level['integral'];
//                    $levelShopIntegral = $level['shop_integral'];
//                    $lastLevelId = $level['levelId'];
//                    break;
//                }
//            }
//            if ($levelIntegral && ($lastLevelId > 0) && isset($levelShopIntegral)) {
//                if (($user['add_integral'] >= $levelIntegral) && ($user['shop_integral'] >= $levelShopIntegral)) {
//                    //DB::name('userhome')->where(['id' => $value['userId']])->update(['levelId' => $lastLevelId]);
//                }
//            }
//        }
        return var_dump($user);
        $user = DB::name('userhome')->where('id', 610)->find();
        $break = "红包测试";
        $openid = null;
        $appId = null;
        if (isset($user['appletOpenid']) && !empty($user['appletOpenid'])) {
            $openid = $user['appletOpenid'];
            $appId = "wx4a40935421da4a92";
        } else {
            if (isset($user['appOpenid']) && !empty($user['appOpenid'])) {
                $openid = $user['appOpenid'];
                $appId = "wx09c4b8eabf581e35";
            }
        }

        //$request = Request::instance();
        include './WeixinPay.php';
        $wx = new \WeixinPay();//实例化微信支付控制器
        $order = $wx->sendRedPrice($openid, $break, $appId);
        return var_dump($order);
        //dump($order);die;
        if (isset($order['code_url'])) {//判断返回参数中是否有prepay_id
            //$order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            //dump($order1);die;
            $this->success('成功', $order['code_url'], 200);
        } else {
            $this->error('失败', $order['return_msg'], 201);
        }

        return var_dump($user);
        $user = DB::name('userhome')->select();
        $userIdList = [];
        foreach ($user as $key => $value) {
            $userIdList[$key]['userId'] = $value['id'];
        }
        DB::name('user_invite_num')->insertAll($userIdList);
        return var_dump(213);
        $ch = curl_init();
        $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . request()->ip();;
        //用curl发送接收数据
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求为https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $location = curl_exec($ch);
        curl_close($ch);
        //转码
        $location = mb_convert_encoding($location, 'utf-8', 'GB2312');
        //var_dump($location);
        //截取{}中的字符串
        $location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
        //将截取的字符串$location中的‘，’替换成‘&’   将字符串中的‘：‘替换成‘=’
        $location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
        //php内置函数，将处理成类似于url参数的格式的字符串  转换成数组
        parse_str($location, $ip_location);
        return $ip_location['addr'];
        return var_dump(123);
        $arr = DB::name('useraddress')->select();
        foreach ($arr as $value) {
            $pro_id = DB::name('district')->where('level', 1)->where('district', $value['pro_name'])->find();
            if ($pro_id) {
                $city = explode("市", $value['city_name']);
                $city_id = DB::name('district')->where('level', 2)->where('pid', $pro_id['district_id'])->where('district', 'like', '%' . $city[0] . '%')->find();
                if ($city_id) {
                    $area_id = DB::name('district')->where('level', 3)->where('pid', $city_id['district_id'])->where('district', $value['area_name'])->find();
                    if ($area_id) {
                        $data = [];
                        $data['pro_id'] = $pro_id['district_id'];
                        $data['city_id'] = $city_id['district_id'];
                        $data['area_id'] = $area_id['district_id'];
                        $data['pro_name'] = $pro_id['district'];
                        $data['city_name'] = $city_id['district'];
                        $data['area_name'] = $area_id['district'];
                        DB::name('useraddress')->where('id', $value['id'])->update($data);
                    } else {
                        DB::name('useraddress')->where('id', $value['id'])->delete();
                    }
                } else {
                    DB::name('useraddress')->where('id', $value['id'])->delete();
                }
            } else {
                DB::name('useraddress')->where('id', $value['id'])->delete();
            }
        }
        return var_dump(21312);
//        Db::name("userhome")->whereRaw('id != 0')->update(['spend'=>0]);
//        $order = Db::name("order")->whereIn('status',[2,3,4,5,6])->select();
//        foreach ($order as $value){
//            Db::name("userhome")->where('id',$value['userhome_id'])->setInc('spend',$value['allprice']);
//        }
        return var_dump(2132);
        $supplierList = Db::name("supplier")->where('is_del', 1)->select();
        $supplierIdList = null;
        $supplierIdLists = [];
        foreach ($supplierList as $value) {
            $supplierIdLists[] = $value['id'];
            if ($supplierIdList) {
                $supplierIdList .= ',' . $value['id'];
            } else {
                $supplierIdList = $value['id'];
            }
        }
        Db::name("supplier_order_tj")->whereIn('supplier_id', $supplierIdLists)->delete();
        $this->success('成功', $supplierIdLists, 200);
    }
//
//    public function getSupplierFreight()
//    {
//        $pageSize = $this->request->param('pageSize') ?: 10;
//        $supplierId = $this->request->param('supplierId');
//
//        $supplierFreightList = Db::name("supplier_freight")->where('supplierId', $supplierId)->order('createTime', 'DESC')->paginate($pageSize);
//        $data = [];
//        $data['supplierFreightList'] = $supplierFreightList->items();
//        $data['totalNum'] = $supplierFreightList->total();
//        $this->success('成功', $data, 200);
//    }
//
//    public function showSupplierFreight()
//    {
//        $supplierFreightId = $this->request->param('supplierFreightId');
//        $supplierFreight = Db::name("supplier_freight")->where('supplierFreightId', $supplierFreightId)->find();
//        if ($supplierFreight) {
//            $supplierFreightDetailList = Db::name("supplier_freight_detail")->where('supplierFreightId', $supplierFreightId)->select();
//            foreach ($supplierFreightDetailList as $key => $value) {
//                if(isset($value['freightList']) && !empty($value['freightList'])){
//                    $freightJsonList = json_decode($value['freightList']);
//                    $freightList = [];
//                    foreach ($freightJsonList as $k=>$v){
//                        $freightList[$k]['num'] = $v->num;
//                        $freightList[$k]['price'] = $v->price;
//                    }
//                    $supplierFreightDetailList[$key]['freightList'] = $freightList;
//                }
//                if(isset($value['districtIdList']) && !empty($value['districtIdList'])){
//                    $supplierFreightDetailList[$key]['districtIdList'] = json_decode($value['districtIdList']);
//                }
//                if(isset($value['districtNameList']) && !empty($value['districtNameList'])){
//                    $supplierFreightDetailList[$key]['districtNameList'] = json_decode($value['districtNameList']);
//                }
//            }
//            $supplierFreight['supplierFreightDetailList'] = $supplierFreightDetailList;
//        }
//        //return var_dump($supplierFreight);
//        $this->success('成功', $supplierFreight, 200);
//
//    }
//
//    public function storeSupplierFreight()
//    {
//        $data = $this->request->post();
//        if(!isset($data['supplierId']) || !isset($data['freightName']) || !isset($data['type'])){
//            $this->error("请检查必传参数");
//        }
//        try {
//            Db::startTrans();
//            $supplierFreightId = $data['supplierFreightId'];
//            $time = date("Y-m-d H:i:s");
//            $supplierFreight = [];
//            $supplierFreight['freightName'] = $data['freightName'];
//            $supplierFreight['type'] = $data['type'];
//            $supplierFreight['logisticsName'] = $data['logisticsName'];
//            if($supplierFreightId){
//                //修改
//                Db::name("supplier_freight")->where('supplierFreightId', $supplierFreightId)->update($supplierFreight);
//            }else{
//                //添加
//                $supplierFreight['supplierId'] = $data['supplierId'];
//                $supplierFreight['createTime'] = $time;
//                $supplierFreightId = Db::name("supplier_freight")->insertGetId($supplierFreight);
//            }
//            Db::name("supplier_freight_detail")->where('supplierFreightId', $supplierFreightId)->delete();
//            if(isset($data['supplierFreightDetailList'][0])){
//                $supplierFreightDetailList = [];
//                foreach ($data['supplierFreightDetailList'] as $key=>$value){
//                    $supplierFreightDetailList[$key]['supplierFreightId'] = $supplierFreightId;
//                    $supplierFreightDetailList[$key]['type'] = $value['type'];
//                    if(!isset($value['freightList']) || empty($value['freightList'])){
//                        $this->error("运费规则不可为空");
//                    }
//                    $supplierFreightDetailList[$key]['districtNameList'] = json_encode($value['districtNameList']);
//                    $supplierFreightDetailList[$key]['districtIdList'] = json_encode($value['districtIdList']);
//                    $supplierFreightDetailList[$key]['freightList'] = json_encode($value['freightList']);
//                }
//                Db::name("supplier_freight_detail")->insertAll($supplierFreightDetailList);
//            }
//
//            Db::commit();
//        } catch (ValidateException $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        } catch (PDOException $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//        $this->success('成功', true, 200);
//    }
//
//    public function deleteSupplierFreight()
//    {
//        $supplierFreightId = $this->request->param('supplierFreightId');
//        Db::name("supplier_freight")->where('supplierFreightId', $supplierFreightId)->delete();
//        Db::name("supplier_freight_detail")->where('supplierFreightId', $supplierFreightId)->delete();
//        $this->success('成功', true, 200);
//    }
//    public function getCollaborate()
//    {
//        $pageSize = $this->request->param('pageSize') ?: 10;
//        $uid = $this->request->param('uid');
//        $nickname = $this->request->param('nickname');
//        $phone = $this->request->param('phone');
//        $status = $this->request->param('status');
//        $createStartTime = $this->request->param('createStartTime');
//        $createEndTime = $this->request->param('createEndTime');
//
//        $sql = Db::name("user_collaborate t1")
//            ->join('userhome t2', 't1.userId=t2.id');
//        if (isset($uid) && !empty($uid)) {
//            $sql->where('t2.id', 'like', "%$uid%");
//        }
//        if (isset($nickname) && !empty($nickname)) {
//            $sql->where('t2.nickname', 'like', "%$nickname%");
//        }
//        if (isset($phone) && !empty($phone)) {
//            $sql->where('t2.phone', 'like', "%$phone%");
//        }
//        if (isset($status) && !empty($status)) {
//            $sql->where('t1.status', $status);
//        }
//        if (isset($createStartTime) && !empty($createStartTime)) {
//            $sql->where('t1.createTime', ">=", $createStartTime);
//        }
//        if (isset($createEndTime) && !empty($createEndTime)) {
//            $sql->where('t1.createTime', "<=", $createEndTime);
//        }
//        $list = $sql->order('t1.createTime', "desc")
//            ->field('t1.id,t2.id as uid,t1.status,t1.createTime,t2.nickname,t2.phone,t2.grandPrice,t2.lockPrice,t2.consumePrice,t2.withdrawPrice')
//            ->paginate($pageSize);
//        $collaborateList = $list->items();
//        foreach ($collaborateList as $key => $value) {
//            $collaborateList[$key]['userNum'] = DB::name('user_team')->where('teamUserId', $value['uid'])->where('status', 1)->count();
//            $collaborateList[$key]['userPTNum'] = DB::name('user_team t1')
//                ->join('userhome t2', 't1.userId=t2.id')
//                ->where('t1.teamUserId', $value['uid'])
//                ->where('t2.levelId', 1)
//                ->where('status', 1)->count();
//            $collaborateList[$key]['userBYNum'] = DB::name('user_team t1')
//                ->join('userhome t2', 't1.userId=t2.id')
//                ->where('t1.teamUserId', $value['uid'])
//                ->where('t2.levelId', 2)
//                ->where('status', 1)->count();
//            $collaborateList[$key]['userHJNum'] = DB::name('user_team t1')
//                ->join('userhome t2', 't1.userId=t2.id')
//                ->where('t1.teamUserId', $value['uid'])
//                ->where('t2.levelId', 3)
//                ->where('status', 1)->count();
//            $collaborateList[$key]['userBJNum'] = DB::name('user_team t1')
//                ->join('userhome t2', 't1.userId=t2.id')
//                ->where('t1.teamUserId', $value['uid'])
//                ->where('t2.levelId', 4)
//                ->where('status', 1)->count();
//            $collaborateList[$key]['userZSNum'] = DB::name('user_team t1')
//                ->join('userhome t2', 't1.userId=t2.id')
//                ->where('t1.teamUserId', $value['uid'])
//                ->where('t2.levelId', 5)
//                ->where('status', 1)->count();
//        }
//        $data = [];
//        $data['collaborateList'] = $collaborateList;
//        $data['totalNum'] = $list->total();
//        $this->success('成功', $data, 200);
//    }
//
//    public function statusCollaborate()
//    {
//        $id = $this->request->param('id');
//        $user_collaborate = Db::name("user_collaborate")->where('id', $id)->find();
//        if ($user_collaborate) {
//            if ($user_collaborate['status']) {
//                Db::name("user_collaborate")->where('id', $id)->update(['status' => 0]);
//            } else {
//                Db::name("user_collaborate")->where('id', $id)->update(['status' => 1]);
//            }
//        }
//        $this->success('成功', true, 200);
//    }
//
//    public function setCollaborate()
//    {
//        $uid = $this->request->param('uid');
//        $phone = $this->request->param('phone');
//        $username = $this->request->param('username');
//        $password = $this->request->param('password');
//        $collaborateId = $this->request->param('collaborateId');
//        if (!$phone || !$username || !$password || !$uid || !$collaborateId) {
//            $this->error('请检查携带参数');
//        }
//        $user_collaborate = DB::name('user_collaborate')->where('username', $username)->find();
//        if ($user_collaborate) {
//            $this->error('已存在该账号');
//        }
//        $user_collaborate = DB::name('user_collaborate')->where('userId', $phone)->find();
//        if ($user_collaborate) {
//            $this->error('该手机号已是供应商');
//        }
//        $user = DB::name('userhome')->where('id', $uid)->where('phone', $phone)->find();
//        if (!$user) {
//            $this->error('该用户不存在');
//        }
//        if ($user['teamUserPhone'] == $user['phone']) {
//            $this->error('该手机号已是供应商');
//        }
//        if ($user['levelId'] != 5) {
//            //$this->error('该用户并非砖石会员');
//        }
//        $userList = DB::name('userhome t1')
//            ->join('user_relation t2', 't1.phone=t2.userPhone')
//            ->where('t2.relationList', "like", "%$phone%")
//            ->where(function ($query) use ($user) {
//                $query->where('t1.teamUserPhone', $user['teamUserPhone'])
//                    ->whereOr('t1.teamUserPhone', null);
//            })
//            ->field('t1.id as uid,t1.teamUserPhone,t2.*')
//            ->select();
//        $time = date("Y-m-d H:i:s");
//        $userIdList = [$user['id']];
//        $userPhoneList = [$user['phone']];
//        $userTeamList = [
//            [
//                'userPhone' => $user['phone'],
//                'inviteUserPhone' => $user['inviteUserPhone'],
//                'teamUserPhone' => $user['phone'],
//                'createTime' => $time
//            ]
//        ];
//        foreach ($userList as $key => $value) {
//            $userIdList[] = $value['uid'];
//            $userPhoneList[] = $value['userPhone'];
//            $userTeamList[$key + 1]['userPhone'] = $value['userPhone'];
//            $userTeamList[$key + 1]['inviteUserPhone'] = $value['inviteUserPhone'];
//            $userTeamList[$key + 1]['teamUserPhone'] = $user['phone'];
//            $userTeamList[$key + 1]['createTime'] = $time;
//        }
//        DB::name('userhome')->whereIn('id', $userIdList)->update(['teamUserPhone' => $user['phone']]);
//        DB::name('user_team')->whereIn('userPhone', $userPhoneList)->update(['status' => 0, 'updateTime' => date("Y-m-d H:i:s")]);
//        DB::name('user_team')->insertAll($userTeamList);
//        $user_collaborate = [];
//        $user_collaborate['userPhone'] = $user['phone'];
//        $user_collaborate['collaborateId'] = $collaborateId;
//        $user_collaborate['createTime'] = $time;
//        $user_collaborate['username'] = $username;
//        $user_collaborate['password'] = md5("liushuiluan$password");
//        DB::name('user_collaborate')->insert($user_collaborate);
//        $this->success('成功', true, 200);
//    }
//
//    public function collaborate()
//    {
//        $collaborate = DB::name('collaborate')->order('id', 'asc')->select();
//        $this->success('成功', $collaborate, 200);
//    }
//
//    public function information()
//    {
//        $pageSize = $this->request->param('pageSize');
//        $informationList = DB::name('information')
//            ->order('createTime', 'asc')
//            ->field('informationId,informationTitle,createTime')
//            ->paginate($pageSize);
//        $data = [];
//        $data['informationList'] = $informationList->items();
//        $data['totalNum'] = $informationList->total();
//        $this->success('成功', $data, 200);
//    }
//
//    public function getCollaborateList()
//    {
//        $keyword = $this->request->param('keyword');
//        $sql = DB::name('user_collaborate t1')
//            ->join('userhome t2', 't1.userPhone=t2.phone');
//        if (isset($keyword) && !empty($keyword)) {
//            $sql->where(function ($query) use ($keyword) {
//                $query->where('t2.id', "like", "%$keyword%")
//                    ->whereOr('t2.nickname', "like", "%$keyword%")
//                    ->whereOr('t2.phone', "like", "%$keyword%");
//            });
//        }
//        $collaborate = $sql->field('t1.id,t2.id as uid,t2.nickname,t2.phone')->order('t1.createTime', 'desc')->select();
//        $this->success('成功', $collaborate, 200);
//    }

//    public function getAfterOrder()
//    {
//        $pageSize = $this->request->param('pageSize') ?: 10;
//        $userhome_id = $this->request->param('userhome_id');
//        $nickname = $this->request->param('nickname');
//        $address = $this->request->param('address');
//        $suppname = $this->request->param('suppname');
//        $wuliu_name = $this->request->param('wuliu_name');
//        $paycode = $this->request->param('paycode');
//        $name = $this->request->param('name');
//        $phone = $this->request->param('phone');
//        $paytype = $this->request->param('paytype');
//        $wuliu_num = $this->request->param('wuliu_num');
//        $ordernum = $this->request->param('ordernum');
//        $status = $this->request->param('status');
//        $createtime = $this->request->param('createtime');
//        $paytime = $this->request->param('paytime');
//        $fahuotime = $this->request->param('fahuotime');
//        $sql = Db::name("orderdetail t1")
//            ->join('order t2', 't1.order_id = t2.id')
//            ->join('supplier t3', 't2.supplier_id = t3.id', "LEFT")
//            ->join('order_return t4', 't1.id = t4.orderdetail_id')
//            ->join('userhome t5', 't2.userhome_id = t5.id');
//        if (isset($userhome_id)) {
//            $sql->where('t5.id', 'like', "%$userhome_id%");
//        }
//        if (isset($nickname)) {
//            $sql->where('t5.nickname', 'like', "%$nickname%");
//        }
//        if (isset($address)) {
//            $sql->where('t2.address', 'like', "%$address%");
//        }
//        if (isset($suppname)) {
//            $sql->where('t3.suppname', 'like', "%$suppname%");
//        }
//        if (isset($wuliu_name)) {
//            $sql->where('t2.wuliu_name', 'like', "%$wuliu_name%");
//        }
//        if (isset($paycode)) {
//            $sql->where('t2.paycode', 'like', "%$paycode%");
//        }
//        if (isset($name)) {
//            $sql->where('t2.name', 'like', "%$name%");
//        }
//        if (isset($phone)) {
//            $sql->where('t2.phone', 'like', "%$phone%");
//        }
//        if (isset($paytype)) {
//            $sql->where('t2.paytype', $paytype);
//        }
//        if (isset($wuliu_num)) {
//            $sql->where('t2.wuliu_num', 'like', "%$wuliu_num%");
//        }
//        if (isset($ordernum)) {
//            $sql->where('t2.ordernum', 'like', "%$ordernum%");
//        }
//        if (isset($status)) {
//            $sql->where('t2.is_shouhou', $status);
//        }
//        if (isset($createtime)) {
//            $v = str_replace(' - ', ',', $createtime);
//            $arr = array_slice(explode(',', $v), 0, 2);
//            if (isset($arr[0])) {
//                $sql->where("t2.createtime >= '" . strtotime($arr[0]) . "'");
//            }
//            if (isset($arr[1])) {
//                $sql->where("t2.createtime <= '" . strtotime($arr[1]) . "'");
//            }
//            //return var_dump($arr);
//        }
//        if (isset($paytime)) {
//            $v = str_replace(' - ', ',', $paytime);
//            $arr = array_slice(explode(',', $v), 0, 2);
//            if (isset($arr[0])) {
//                $sql->where("t2.paytime >= '" . strtotime($arr[0]) . "'");
//            }
//            if (isset($arr[1])) {
//                $sql->where("t2.paytime <= '" . strtotime($arr[1]) . "'");
//            }
//            //return var_dump($arr);
//        }
//        if (isset($fahuotime)) {
//            $v = str_replace(' - ', ',', $fahuotime);
//            $arr = array_slice(explode(',', $v), 0, 2);
//            if (isset($arr[0])) {
//                $sql->where("t2.fahuotime >= '" . strtotime($arr[0]) . "'");
//            }
//            if (isset($arr[1])) {
//                $sql->where("t2.fahuotime <= '" . strtotime($arr[1]) . "'");
//            }
//            //return var_dump($arr);
//        }
//        $list = $sql->where('t4.is_new', 1)
//            ->order('t4.createTime', 'desc')
//            ->field("t1.id as orderdetail_id,t2.id as order_id,t4.id as orderreturn_id,t5.id as userhome_id,t5.nickname,t2.paycode,t1.is_shouhou,t1.image as goodimage,t1.name as goodname,
//                t1.goods_spec_name,t1.num as goodnum,t1.price,t1.price as totalPrice,t1.tkprice,t2.createtime,t1.break,t2.paytype,t3.suppname,t1.cost_price,t1.cost_price as total_cost_price,t1.shuilv,t2.paytime,
//                t2.shouhuotime,t2.shouhuotime,t2.wuliu_code,t2.wuliu_code")
//            ->paginate($pageSize);
//        $orderList = $list->items();
//        foreach ($orderList as $k => $v) {
//            if (isset($v['goodnum']) && !empty($v['goodnum']) && isset($v['price']) && !empty($v['price'])) {
//                $orderList[$k]['totalPrice'] = $v['goodnum'] * $v['price'];
//            }
//            if (isset($v['goodnum']) && !empty($v['goodnum']) && isset($v['cost_price']) && !empty($v['cost_price'])) {
//                $orderList[$k]['total_cost_price'] = $v['goodnum'] * $v['cost_price'];
//            }
//        }
//        $result = array("total" => $list->total(), "rows" => $orderList);
//        $this->success('成功', $result, 200);
//    }
//
//    public function upBreak()
//    {
//        $orderdetail_id = $this->request->param("orderdetail_id");//订单详情id
//        $break = $this->request->param("break");//备注
//        if (!$orderdetail_id || !$break) {
//            $this->error('参数不完整,请校验传入参数', '', 30059);
//        }
//        Db::name("orderdetail")->where('id',$orderdetail_id)->update(['break'=>$break]);
//        $this->success('成功', '成功', 200);
//    }
//
//    public function getAfterOrderShow()
//    {
//        $orderdetail_id = $this->request->param('orderdetail_id');
//        $orderDetail = Db::name("orderdetail t1")
//            ->join('order t2', 't1.order_id = t2.id')
//            ->join('supplier t3', 't2.supplier_id = t3.id', "LEFT")
//            ->where('t1.id', $orderdetail_id)
//            ->field("t1.id as orderdetail_id,t2.id as order_id,t2.paycode,t1.is_shouhou,t1.image as goodimage,t1.name as goodname,
//                t1.goods_spec_name,t1.num as goodnum,t1.price,t1.price as totalPrice,t1.tkprice,t2.createtime,t2.paytype,t3.suppname,t1.cost_price,t1.cost_price as total_cost_price,t1.shuilv,t2.paytime,
//                t2.shouhuotime,t2.shouhuotime,t2.wuliu_code,t2.wuliu_code")
//            ->find();
//        if (isset($orderDetail['goodnum']) && !empty($orderDetail['goodnum']) && isset($orderDetail['price']) && !empty($orderDetail['price'])) {
//            $orderDetail['totalPrice'] = $orderDetail['goodnum'] * $orderDetail['price'];
//        }
//        if (isset($orderDetail['goodnum']) && !empty($orderDetail['goodnum']) && isset($orderDetail['cost_price']) && !empty($orderDetail['cost_price'])) {
//            $orderDetail['total_cost_price'] = $orderDetail['goodnum'] * $orderDetail['cost_price'];
//        }
//        $orderReturn = Db::name("order_return")
//            ->where('orderdetail_id', $orderdetail_id)
//            ->order('is_new', 'desc')
//            ->order('createTime', 'desc')
//            ->select();
//        foreach ($orderReturn as $key => $value) {
//            if (isset($value['image']) && !empty($value['image'])) {
//                unset($k);
//                unset($v);
//                $image = explode(';', $value['image']);
//                $return_image_list = [];
//                foreach ($image as $k => $v) {
//                    $return_image_list[] = path($v);
//                }
//                $orderReturn[$key]['image'] = $return_image_list;
//            }
//            if (isset($value['service_image']) && !empty($value['service_image'])) {
//                unset($k);
//                unset($v);
//                $image = explode(';', $value['service_image']);
//                $service_image_list = [];
//                foreach ($image as $k => $v) {
//                    $service_image_list[] = path($v);
//                }
//                $orderReturn[$key]['service_image'] = $service_image_list;
//            }
//        }
//        $orderDetail['orderReturn'] = $orderReturn;
//        $this->success('成功', $orderDetail, 200);
//    }
//
//    public function setafterorder()
//    {
//        $service_image = $this->request->param('service_image');
//        $service_break = $this->request->param('service_break');
//        $shouhou_status = $this->request->param('shouhou_status');
//        $orderreturn_id = $this->request->param('orderreturn_id');
//        $sjtkprice = $this->request->param('sjtkprice');
//        $orderReturn = Db::name("order_return")
//            ->where('id', $orderreturn_id)
//            ->find();
//        if (!$orderReturn['is_new']) {
//            $this->error('该售后记录不是最新记录,请勿操作', '', 30021);
//        }
//        if ($orderReturn['shouhou_status']) {
//            $this->error('该售后记录已处理,请勿操作', '', 30022);
//        }
//        $order = Db::name("order")
//            ->where('id', $orderReturn['order_id'])
//            ->find();
//        if ($order['status'] == 5 || $order['status'] == 4) {
//            $this->error('该订单已完成，无法再次进行售后', '', 30023);
//        }
//        $orderDetail = Db::name("orderdetail")
//            ->where('id', $orderReturn['orderdetail_id'])
//            ->find();
//        if ($orderDetail['is_shouhou'] != 1) {
//            $this->error('该售后记录已处理，无法再次进行售后', '', 30022);
//        }
//        if (intval(strval($sjtkprice * 100)) > intval(strval($orderDetail['tkprice'] * 100))) {
//            $this->error('退款金额无法大于预计退款金额', '', 30024);
//        }
//        $content = null;
//        if ($shouhou_status == 1) {
//            if ($orderReturn['return_type'] == "MONEY") {
//                //仅退款
//                $this->refund($sjtkprice,$order,$orderDetail);
//                Db::name("order_return")
//                    ->where('id', $orderreturn_id)
//                    ->update(['shouhou_status' => 1, 'schedule' => "COMPELETE",'return_price'=>$sjtkprice, 'service_image' => $service_image, 'service_break' => $service_break, 'updateTime' => date("Y-m-d H:i:s")]);
//                $content = "商家已同意退款";
//            } else if ($orderReturn['return_type'] == "HAM") {
//                //退货退款
//                Db::name("order_return")
//                    ->where('id', $orderreturn_id)
//                    ->update(['shouhou_status' => 1, 'schedule' => "RETERUN", 'service_image' => $service_image, 'service_break' => $service_break, 'updateTime' => date("Y-m-d H:i:s")]);
//                $content = "商家已同意退货退款,请尽快退货,退货地址请联系客服";
//            }
//        } else {
//            Db::name("order_return")
//                ->where('id', $orderreturn_id)
//                ->update(['shouhou_status' => 2, 'schedule' => "COMPELETE", 'service_image' => $service_image, 'service_break' => $service_break, 'updateTime' => date("Y-m-d H:i:s")]);
//            Db::name("orderdetail")
//                ->where('id', $orderReturn['orderdetail_id'])
//                ->update(['is_shouhou' => 3]);
//            Db::name("order")
//                ->where('id', $orderReturn['order_id'])
//                ->update(['is_shouhou' => 2,'status'=>$order['oldStatus']]);
//            $content = "商家拒绝退款,理由为:".$service_break;
//        }
//        $order_negotiation_history = [
//            'order_id'=>$orderReturn['order_id'],
//            'orderdetail_id'=>$orderReturn['orderdetail_id'],
//            'order_return_id'=>$orderReturn['id'],
//            'content'=>$content,
//            'image'=>$service_image,
//            'break'=>$service_break,
//            'shouhou_status'=>$shouhou_status
//        ];
//        Db::name("yc_order_negotiation_history")->insert($order_negotiation_history);
//        $this->success('成功', '完成', 200);
//    }
//
//    public function setAfterOrderHarvest()
//    {
//        $service_image = $this->request->param('service_image');
//        $service_break = $this->request->param('service_break');
//        $shouhou_status = $this->request->param('shouhou_status');
//        $orderreturn_id = $this->request->param('orderreturn_id');
//        $sjtkprice = $this->request->param('sjtkprice');
//        $orderReturn = Db::name("order_return")
//            ->where('id', $orderreturn_id)
//            ->find();
//        if (!$orderReturn['is_new']) {
//            $this->error('该售后记录不是最新记录,请勿操作', '', 30021);
//        }
//        if ($orderReturn['return_type'] != "HAM") {
//            $this->error('该售后并非退货退款,请勿操作', '', 30024);
//        }
//        if ($orderReturn['schedule'] != "RETERUN") {
//            $this->error('该售后并未进行第一步确认,请勿越级操作', '', 30025);
//        }
//        $order = Db::name("order")
//            ->where('id', $orderReturn['order_id'])
//            ->find();
//        if ($order['status'] == 5 || $order['status'] == 4) {
//            $this->error('该订单已完成，无法再次进行售后', '', 30023);
//        }
//        $orderDetail = Db::name("orderdetail")
//            ->where('id', $orderReturn['orderdetail_id'])
//            ->find();
//        if ($orderDetail['is_shouhou'] != 1) {
//            $this->error('该售后记录已处理，无法再次进行售后', '', 30022);
//        }
//        if (intval(strval($sjtkprice * 100)) > intval(strval($orderDetail['tkprice'] * 100))) {
//            $this->error('退款金额无法大于预计退款金额', '', 30024);
//        }
//        if ($shouhou_status == 1) {
//            $this->refund($sjtkprice,$order,$orderDetail);
//            Db::name("order_return")
//                ->where('id', $orderreturn_id)
//                ->update(['shouhou_status' => 1, 'schedule' => "COMPELETE",'return_price'=>$sjtkprice, 'service_image' => $service_image, 'service_break' => $service_break, 'updateTime' => date("Y-m-d H:i:s")]);
//            $content = "商家已同意退款";
//        } else {
//            Db::name("order_return")
//                ->where('id', $orderreturn_id)
//                ->update(['shouhou_status' => 2, 'schedule' => "COMPELETE", 'service_image' => $service_image, 'service_break' => $service_break, 'updateTime' => date("Y-m-d H:i:s")]);
//            Db::name("orderdetail")
//                ->where('id', $orderReturn['orderdetail_id'])
//                ->update(['is_shouhou' => 3]);
//            Db::name("order")
//                ->where('id', $orderReturn['order_id'])
//                ->update(['is_shouhou' => 2,'status'=>$order['oldStatus']]);
//            $content = "商家拒绝退款,理由为:".$service_break;
//        }
//        $order_negotiation_history = [
//            'order_id'=>$orderReturn['order_id'],
//            'orderdetail_id'=>$orderReturn['orderdetail_id'],
//            'order_return_id'=>$orderReturn['id'],
//            'content'=>$content,
//            'image'=>$service_image,
//            'break'=>$service_break,
//            'shouhou_status'=>$shouhou_status
//        ];
//        Db::name("yc_order_negotiation_history")->insert($order_negotiation_history);
//        $this->success('成功', '完成', 200);
//    }
//    // /确认退款
//    public function refund($returnPrice,$order,$orderdetail)
//    {
//        $payType = $order['paytype'];
//        $paycode = $order['paycode'];
//        if ($payType == 1) {//微信退款
//            require_once "./WinXinRefund.php";
//            $openid = '';
//            $outTradeNo = $paycode;//单号
//            $totalFee = $order['allprice'] * 100;//订单总金额，单位为分，只能为整数
//            $refundFee = $returnPrice * 100;//退款总金额订单总金额单位为分只能为整数
//            // $totalFee = 1;//订单总金额，单位为分，只能为整数
//            // $refundFee = 1;//退款总金额订单总金额单位为分只能为整数
//            //判断实际退款是否为0
//            if ($refundFee > 0) {
//                // code...
//                $outRefundNo = date("Ymd") . time();
//                $WinXinRefund = new \WinXinRefund($openid, $outTradeNo, $totalFee, $outRefundNo, $refundFee);
//                $result = $WinXinRefund->refund();
//                // dump($result);die;
//                // 更新退款信息
//                if ($result['return_code'] == "SUCCESS") {
//                    if ($result['result_code'] == "SUCCESS") {
//                        // 退款完成更改订单状态
//                        DB::name('orderdetail')->where('id', $orderdetail['id'])->update(['is_shouhou' => 2,'sjtkprice'=>$returnPrice]);//2=已完成,3=已拒绝
//                        $orderDetailNum = DB::name('orderdetail')->where('order_id', $order['id'])->where('is_shouhou','!=',2)->count();
//                        if(!$orderDetailNum){
//                            DB::name('order')->where('id', $order['id'])->update(['status' => 5,'is_shouhou'=>2]);
//                        }else{
//                            $orderDetailNum = DB::name('orderdetail')->where('order_id', $order['id'])->where('is_shouhou','!=',1)->where('is_shouhou','!=',2)->count();
//                            if(!$orderDetailNum){
//                                DB::name('order')->where('id', $order['id'])->update(['status' => $order['oldStatus'],'is_shouhou'=>2]);
//                            }
//                        }
//                        //推送消息
//                        $logistics = [
//                            'name' => '您的订单号:' . $order['ordernum'] . '已经完成退款,详情已到账为准',
//                            'createtime' => time(),
//                            'userhome_id' => $order['userhome_id'],
//                            'order_id' => $order['id']
//                        ];
//                        // unset($order['ordernum']);
//                        DB::name('logistics')->insertGetId($logistics);
//                        jpush_stu_single($order['userhome_id'], $logistics['name'], '', 2);//2=订单消息
//                    } else {
//                        $this->error("操作失败");
//                    }
//                } else {
//                    $this->error("操作失败");
//                }
//            }
//        }
//        if ($payType == 2) {//支付宝退款
//            $yue_sn = $paycode;
//            // dump($paycode);die;
//            $out_request_no = time();//部分退款
//            // include "./alipay/aop/AopClient.php";
//            // include "./alipay/aop/AopCertClient.php";
//            // include "./alipay/aop/request/AlipayTradeRefundRequest.php";
//            // $c = new \AopCertClient;
//            // $appCertPath = "/home/wwwroot/php-zhjz/public/cert/appCertPublicKey_2021002110647757.crt";//应用公钥
//            // $alipayCertPath = "/home/wwwroot/php-zhjz/public/cert/alipayCertPublicKey_RSA2.crt";//支付宝公钥
//            // $rootCertPath = "/home/wwwroot/php-zhjz/public/cert/alipayRootCert.crt";//支付宝根证书
//            // $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
//            // $c->appId = "2021002110647757";
//            //支付宝
//            include "./aop/AopClient.php";
//            include "./aop/AopCertClient.php";
//            include "./aop/request/AlipayTradeRefundRequest.php";
//            $c = new \AopCertClient;
//            $appCertPath = "/home/wwwroot/php-yc1/public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
//            $alipayCertPath = "/home/wwwroot/php-yc1/public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
//            $rootCertPath = "/home/wwwroot/php-yc1/public/zhengshu/alipayRootCert.crt";//支付宝根证书
//            $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
//            $c->appId = "2021002182617884";
//            $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
//            $c->format = "json";
//            $c->charset = "GBK";
//            $c->signType = "RSA2";
//            //调用getPublicKey从支付宝公钥证书中提取公钥
//            $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
//            //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
//            $c->isCheckAlipayPublicCert = true;
//            //调用getCertSN获取证书序列号
//            $c->appCertSN = $c->getCertSN($appCertPath);
//            //调用getRootCertSN获取支付宝根证书序列号
//            $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);
//            //判断抵扣券是否大于0
//            $refundFee = $returnPrice;
//            if ($refundFee > 0) {
//                // code...
//                $request2 = new \AlipayTradeRefundRequest();
//                //SDK已经封装掉了公共参数，这里只需要传入业务参数
//                $bizcontent = "{\"out_trade_no\": \"{$yue_sn}\","
//                    . "\"refund_amount\": \"$refundFee\","
//                    . "\"out_request_no\": \"{$out_request_no}\""
//                    . "}";
//                $request2->setBizContent($bizcontent);
//                $result = $c->execute($request2);
//                // dump($result);die;
//                $responseNode = str_replace(".", "_", $request2->getApiMethodName()) . "_response";
//                $resultCode = $result->$responseNode->code;
//                if (!empty($resultCode) && $resultCode == 10000) {
//                    DB::name('orderdetail')->where('id', $orderdetail['id'])->update(['is_shouhou' => 2,'sjtkprice'=>$returnPrice]);//2=已完成,3=已拒绝
//                    $orderDetailNum = DB::name('orderdetail')->where('order_id', $order['id'])->where('is_shouhou','!=',2)->count();
//                    if(!$orderDetailNum){
//                        DB::name('order')->where('id', $order['id'])->update(['status' => 5,'is_shouhou'=>2]);
//                    }else{
//                        $orderDetailNum = DB::name('orderdetail')->where('order_id', $order['id'])->where('is_shouhou','!=',1)->where('is_shouhou','!=',2)->count();
//                        if(!$orderDetailNum){
//                            DB::name('order')->where('id', $order['id'])->update(['status' => $order['oldStatus'],'is_shouhou'=>2]);
//                        }
//                    }
//                    //推送消息
//                    $logistics = [
//                        'name' => '您的订单号:' . $order['ordernum'] . '已经完成退款,详情已到账为准',
//                        'createtime' => time(),
//                        'userhome_id' => $order['userhome_id'],
//                        'order_id' => $order['id']
//                    ];
//                    // unset($order['ordernum']);
//                    DB::name('logistics')->insertGetId($logistics);
//                    jpush_stu_single($order['userhome_id'], $logistics['name'], '', 2);//2=订单消息
//                } else {
//                    $sub_msg = $result->$responseNode->sub_msg;
//                    $this->success('失败', $sub_msg, 201);
//                }
//            }
//        }
//    }
}
